package com.CMUBiS.Depreciated;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

import com.CMUBiS.Data.GlobalVars;

/**
 * This servlet registers a new user in the database
 * 
 * @author Andy Turner
 * @version 0.1
 * @since 0.1
 * @date 04/05/2011
 * 
 */
@WebServlet(name="RegisterUserServletOld", urlPatterns="/registeruserold")
public class RegisterUserServlet extends HttpServlet {
	
	private static final long serialVersionUID = 6475041006628438743L;
	private static final String EMPTY = "";
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		StringBuffer errorString = new StringBuffer();
		Map<String, String[]> paramMap = request.getParameterMap();
		
		System.out.println("firstname: " + request.getParameter("firstName"));
		System.out.println("username: " + request.getParameter("username"));
		System.out.println("email: " + request.getParameter("email1"));
		System.out.println("pass: " + request.getParameter("password1"));
		
		
		// If there are parameters passed we need to check they are correct before we can register a user
		if(!paramMap.isEmpty()){
			// Check the username is correct
			if(paramMap.containsKey("username")){
				if(request.getParameter("username").equals(EMPTY)){
					errorString.append("You must provide a username. <br />");
				}
				
				// We must check that the username does not already exist
				else if(GlobalVars.db.usernameExists(request.getParameter("username"))){
					errorString.append("Sorry, the username you have entered is already in use. <br />");
				}
			}
			else{
				errorString.append("You must provide a username. <br />");
			}
			
			// Check the email address is correct
			if(paramMap.containsKey("email1")){
				if(request.getParameter("email1").equals(EMPTY)){
					errorString.append("You must provide an e-mail address. <br />");
				}
				
				else if(!request.getParameter("email1").equals(request.getParameter("email2"))){
					errorString.append("The e-mail addresses you have entered must match. <br />");
				}
				
				// We must check that the email address does not already exist
				else if(GlobalVars.db.emailExists(request.getParameter("email1"))){
					errorString.append("Sorry, the e-mail address you have entered is already registered. <br />");
				}	
			}
			else{
				errorString.append("You must provide an e-mail address. <br />");
			}
			
			// Check the password is correct
			if(paramMap.containsKey("password1")){
				if(request.getParameter("password1").equals(EMPTY)){
					errorString.append("You must provide a password. <br />");
				}
				
				else if(!request.getParameter("password1").equals(request.getParameter("password2"))){
					errorString.append("The passwords you have entered must match. <br />");
				}
			}
			else{
				errorString.append("You must provide a password. <br />");
			}
			
			// Check the first name
			if(!paramMap.containsKey("firstName") || request.getParameter("firstName").equals(EMPTY)){
				errorString.append("You must provide your first name. <br />");
			}
			
			// Check the last name
			if(!paramMap.containsKey("lastName") || request.getParameter("lastName").equals(EMPTY)){
				errorString.append("You must provide your last name. <br />");
			}
			
			// Check the street
			if(!paramMap.containsKey("street") || request.getParameter("street").equals(EMPTY)){
				errorString.append("You must provide a street address. <br />");
			}
			
			// Check the street
			if(!paramMap.containsKey("town") || request.getParameter("town").equals(EMPTY)){
				errorString.append("You must provide a town. <br />");
			}
			
			// Check the zip
			if(!paramMap.containsKey("zip") || request.getParameter("zip").equals(EMPTY)){
				errorString.append("You must provide a zip code. <br />");
			}
			//TODO: make sure zip is 5 numbers long
			else{
				// TODO: Check that the ZIP only contains numbers (we are not being friendly to non-US people here
			}
			
			// Check the state
			if(!paramMap.containsKey("state") || request.getParameter("state").equals(EMPTY) || request.getParameter("state").equals("0")){
				errorString.append("You must choose your state. <br />");
			}
			
			if(errorString.toString().equals("")){
				boolean success = true;
				
				// Make sure the state and zip are numbers good
				int stateNo = -1;
				int zipNo = -1;
				
				try{
					stateNo = Integer.parseInt(request.getParameter("state"));
				}
				catch(Exception e){
					// This can only occur when people screw with the POST command
					errorString.append("There was an error processing your state. Please try again.");
					success = false;
				}
				
				try{
					zipNo = Integer.parseInt(request.getParameter("zip"));
				}
				catch(Exception e){
					errorString.append("The zip code must only contain numbers.");
					success = false;
				}
				
				if(success && stateNo>0 && zipNo>0){
					// As the user has submitted all of the correct information, we will insert them
					/*success = GlobalVars.db.insertUser(request.getParameter("username"), request.getParameter("password1"), request.getParameter("email1"),
							request.getParameter("firstName"), request.getParameter("lastName"), request.getParameter("street"),
							request.getParameter("town"), zipNo, stateNo);
					*/
					if(success){
						// Now they are a registered user, we should also log then in
						System.out.println("all is good!!");
						response.sendRedirect("./login?username="+request.getParameter("username")+"&password="+request.getParameter("password1")+"&welcome=1");
					}
					else{
						// will occur on DB errors, but user shouldn't know that
						errorString.append("There was an error registering the user. Please try again.");	
					}
				}
			}
			else{
				System.out.println(errorString);
			}
		}
		
		// If we get to here, then there are no parameters or there are errors. We need to reshow the registration page
		makePage(request, response, errorString.toString());
	}
	
	/**
	 *
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		makePage(request, response, "");
	}
	
	public void makePage(HttpServletRequest request, HttpServletResponse response, String errorString)  throws ServletException, IOException {
		// We are using PrintWriter to be friendly to the international community. PrintWrite auto-converts coding
		PrintWriter out = response.getWriter();
		
		// Include header
		out.println("<HTML>");
		out.println("<HEAD><TITLE>Register User</TITLE></HEAD>");
		out.println("<BODY>");
		out.println(errorString);
		
		// Do HTML4 or 5 depending on the global variables
		if(GlobalVars.isHTML4)
			createHTML4(request, response, out);
		else
			createHTML5(request, response, out);
	}
	
	public HttpServletResponse createHTML4(HttpServletRequest request, HttpServletResponse response, PrintWriter out){
		try{
			if(GlobalVars.debug){
				System.out.println("RegisterUser (doGet): Getting HTML4 document");
			}
			
			Map<String, String[]> paramMap = request.getParameterMap();
			
			System.out.print(paramMap.containsKey("zip") ? 1 : 2);
			
			// Set the return type
			response.setContentType("text/html");
			
			// Make the input boxes
			out.println("<form name=\"register_user\" action=\"registeruser\" method=\"POST\">");
			out.println("<div id=\"center\">");	
			
			out.println("<div id=\"floatright\">Username: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"username\" size=\"30\" value=\""+ (paramMap.containsKey("username") ?  request.getParameter("username") : "") + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Password: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"password1\" size=\"30\" value=\""+ (paramMap.containsKey("password1") ?  request.getParameter("password1") : "") + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Confirm Password: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"password2\" size=\"30\" value=\""+ (paramMap.containsKey("password2") ?  request.getParameter("password2") : "") + "\"/> </div>");
			
			out.println("<div id=\"floatright\">E-mail address: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"email1\" size=\"30\" value=\""+ (paramMap.containsKey("email1") ?  request.getParameter("email1") : "") + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Confirm E-mail address: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"email2\" size=\"30\" value=\""+ (paramMap.containsKey("email2") ?  request.getParameter("email2") : "") + "\"/> </div>");
			
			out.println("<div id=\"floatright\">First name: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"firstName\" size=\"30\" value=\""+ (paramMap.containsKey("firstName") ?  request.getParameter("firstName") : "") + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Last name: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"lastName\" size=\"30\" value=\""+ (paramMap.containsKey("lastName") ?  request.getParameter("lastName") : "") + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Street: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"street\" size=\"50\" value=\""+ (paramMap.containsKey("street") ?  request.getParameter("street") : "") + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Town: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"town\" size=\"50\" value=\""+ (paramMap.containsKey("town") ?  request.getParameter("town") : "") + "\"/> </div>");
			
			out.println("<div id=\"floatright\">Zip code: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"zip\" size=\"5\" maxlength=\"5\" value=\""+ (paramMap.containsKey("zip") ?  request.getParameter("zip") : "") + "\"/> </div>");
			
			out.println("<div id=\"floatright\">State: </div>");
			out.println("<div id=\"floatcenter\">");
			
			// Set the option that should be selected by default
			int selected = 0;
			try{
				if(paramMap.containsKey("state"))
					selected = Integer.parseInt(request.getParameter("state"));
			}
			catch(Exception e){
				selected = 0;
			}
			
			System.out.println("from url: " + request.getParameter("state") + " in code: " + selected);
			
			out.println("<select name=\"state\">");
			out.println("<option value=\"0\""+ (selected==0?" SELECTED":"") + ">Please Select...</option>");
			
			// Get states from database and add to page
			ArrayList<String[]> states = GlobalVars.db.getStates();
			int length = states.size();
			for(int i=0; i<length; i++){
				String[] state = states.get(i);
				out.println("<option value=\"" + state[0] + "\"" + (selected==i+1?" SELECTED":"") + ">" + state[1] + " - " + state[2] + "</option>");
			}
			
			out.println("</select>");
			out.println("</div>");
			
			out.println("<div id=\"floatright\"><input type=\"submit\" value=\"Register\"></div>");
			
			out.println("</div>");
			out.println("</form>");
			
			// Include footer
			out.println("</BODY></HTML>");
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		return response;
	}
	
	public HttpServletResponse createHTML5(HttpServletRequest request,HttpServletResponse response, PrintWriter out){
		try{
			if(GlobalVars.debug){
				System.out.println("RegisterUser (doGet): Getting HTML5 document");
			}
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return response;
	}
}
